﻿
#region NameSpace
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Purchase;
using System.ComponentModel;
using System.Drawing;
using System.Web.SessionState;
using System.IO;
using System.Text;
using System.Net;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using EB.BPARequestManagement;
using Eb.MessageBox;
using System.Collections.Specialized;
using EB.Inbox;
using ebird.eBirdGenerics;
using ebird.ErrorHandlerHelper;
#endregion

public partial class Modules_Purchase_PurchaseOrderRequest : System.Web.UI.UserControl
{
    #region Fields
    EB.Inbox.Inbox inBoxCreate = new EB.Inbox.Inbox();
    RequestCreate requestCreate = new RequestCreate();
    Purchase.Purchase purchase=new Purchase.Purchase();
    ebird.ErrorHandlerHelper.ErrorLog errorLog = new ebird.ErrorHandlerHelper.ErrorLog();

    static double grdTotal = 0;
    static double grdTotalGeneral = 0;
    static double grdTotalGeneral1 = 0;
    static int generalPurchaseUniqId = 0;
    static int linkKey = 0;
    private double runningTotal = 0;
    int requestType = 0;
    int purchaseRequestUniqId = 0;
    static double expectedAmount = 0;
    static int grdSelectUniqId = 0;
    static int statusId=0;
    static int grdselectGeneralUniqId = 0;
    static int requestListUniqRecordNumber = 0;
    static string requestLinkUniqID = string.Empty;
    static int requestLinkUID = 0;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {

        Stylesheet.Attributes.Add("href", "../../Css/SkylineFair.css");
        Stylesheet.Attributes.Add("type", "text/css");
        Stylesheet.Attributes.Add("rel", "stylesheet");
        TabContainer1.CssClass = "blue";
        GetPriority();
        string pathurl= ((System.Web.HttpRequest)((HttpContext.Current.Request))).Url.AbsoluteUri;
        if(pathurl.ToLower().EndsWith("aspx"))
        {
            if (Session["controlPath"] != null)
            {
                TabContainer1.CssClass = "";
                DiaplayPurchaseRequest();
            }
            else
            {
                Session["hasrequestLinkId"] = null;
                Session["requestTypeId"] = null;
                Session["controlPath"] = null;
                TabContainer1.CssClass = "blue";
                //grvViewGeneralPurchasedItems.CssClass = "grid-view";
            }
        }
        else if (Request.QueryString["Sel"] != null)
        {
            string URL = Request.QueryString["Sel"].ToString();
            string FileName = URL.Substring(URL.LastIndexOf("/") + 1,(URL.Length - URL.LastIndexOf("/") - 1));
            if (FileName == "ucPurchaseOrderRequest.ascx")
            {
                Session["hasrequestLinkId"] = null;
                Session["requestTypeId"] = null;
                Session["controlPath"] = null;
                TabContainer1.CssClass = "blue";
              //  grvViewGeneralPurchasedItems.CssClass = "grid-view";

            }
            else if (FileName == "TaskList.ascx;")
            {
                if (Session["controlPath"] != null)
                {
                    TabContainer1.CssClass = "";
                    TabPanel1.CssClass = "";
                    TabPanel2.CssClass = "";
                    DiaplayPurchaseRequest();
                    btnViewPurchaseOrder.Visible = false;
                    btnViewPurchaseReq.Visible = false;
                    Button6.Visible = false;
                }
            }
        }
        else if (Request.QueryString["linkKey"].ToString() != null && Request.QueryString["RequestType"].ToString() !=null)
        {
            Session["hasrequestLinkId"] = Request.QueryString["linkKey"].ToString();
            Session["requestTypeId"] = Request.QueryString["RequestType"].ToString();
            if( Request.QueryString["RequestType"].ToString()=="1")
            {
                grdSelectUniqId = Convert.ToInt16(Request.QueryString["linkKey"].ToString());
                requestListUniqRecordNumber = Convert.ToInt16(Request.QueryString["ReqUID"].ToString());
            }
            else
            {
                generalPurchaseUniqId = Convert.ToInt16(Request.QueryString["linkKey"].ToString());
            }
            
            DiaplayPurchaseRequest();
            btnProductionUpdate.Visible = true;
            btnViewPurchaseOrder.Visible = true;
            grvMaterialDetails.Enabled = true;
            ddlProductName.Enabled = false;
            txtQty.Enabled = true;
            Button6.Visible = true;
            btnGeneralPurchaseRequestUpdate.Visible = true;
            gvItemDetails.Visible = false;
            grvViewItemDetailsGeneral.Enabled = true;
            btnGeneralPurchaseSubmit.Visible = true;
            btnGeneralPurchaseSubmit1.Visible = true;
            btnGeneralNewPurchaseRequest.Visible = true;
            btnGeneralPurchaseRequestView.Visible = true;
            Button5.Visible = true;
            TabContainer1.Tabs[1].HeaderText = " General ";
            TabContainer1.Tabs[0].HeaderText = "Production";
        }
        else
        {
            DiaplayPurchaseRequest();
            ddlProductName.Enabled = false;
        }

        btnPrint.Attributes.Add("Onclick", "getPrint('Print_All');");
       // btnPrint.Attributes.Add("onclick", "javascript:printPreviewDiv('DivForPrint1')");
       // Button6.Visible = true;
        if (!IsPostBack)
        {
            GetProductionWisePurchasedItems();
            SetInitialRow();
            GetProducts();
            GetGeneralPurchasedItems();
            GetPriority();
           

        }
       if (TabContainer1.ActiveTabIndex == 0)
        {
            requestType = 1;
            
        }
        else
        {
            requestType = 2;
            //btnProductionSave.Visible = false;
            //Button1.Visible = true;
           
        }
     //  GetMaterials();
     
       txtActualLeadTime.Text = DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));
         
       txtGeneralActualLeadDate.Text =DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));
       txtGeneralExpectedLeadDate.Text = DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));
       txtDueDate.Text = DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));
       lblD.Text = DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));
       lblD1.Text = DateReturn(DateTime.Now.ToString("MM-dd-yyyy"));

        

    }

    protected string  DateReturn(string date)
    {
        string result=string.Empty;
        if (date.Contains("-"))
        {
            result = date.Replace("-", "/");
        }
        else
        {
            result = date;
        }
        return result;
    }
    protected void DiaplayPurchaseRequest()
    {
          GetPriority();
        if (Session["hasrequestLinkId"] != null && Session["requestTypeId"] != null)
        {
            btnGeneralPurchaseCompleted.Visible = false;
            btnGeneralNewPurchaseRequest.Visible = false;
            Button6.Visible = false;
            Button4.Visible = false;
            Button1.Visible = false;
            Button2.Visible = false;
            Button3.Visible = false;
            Button5.Visible = false;

            btnGeneralPurchaseRequestView.Visible = false;
            int typeId = purchase.GetPurchaseType(Convert.ToInt16(Session["hasrequestLinkId"]));
            int uniqId = Convert.ToInt16(Session["hasrequestLinkId"]);
            if (typeId == 2)
            {

                grvViewItemDetailsGeneral.Enabled = false;
                TabContainer1.ActiveTabIndex = 1;
                TabContainer1.Tabs[1].HeaderText = string.Empty;
                TabContainer1.Tabs[0].HeaderText = string.Empty;
                // TabContainer2.Enabled = false;
                TabContainer1.Tabs[1].CssClass = "InboxTableHeader";
                TabContainer1.Tabs[0].CssClass = "InboxTableHeader";
                TabPanel1.CssClass = "InboxTableHeader";
                TabPanel2.CssClass = "InboxTableHeader";
                gvItemDetails.CssClass = ".grid-view";
                gvItemDetails.HeaderStyle.CssClass = "grid-view-header";
                gvItemDetails.FooterStyle.CssClass = "grid-view-header";
                // pnlTitlePnl.Visible = false;
                grvViewItemDetailsGeneral.Visible = true;
                btnGeneralForward.Visible = false;
                btnGeneralNewPurchaseRequest.Visible = false;
                btnGeneralPurchaseCompleted.Visible = false;
                btnGeneralSendForApproval.Visible = false;
                btnGeneralPurchaseRequestView.Visible = false;
                Button6.Visible = false;
                DataSet purchaseGeneralDS = purchase.GetPurchaseMasterDetailsByRequestId(uniqId);
                if (purchaseGeneralDS.Tables[0].Rows.Count > 0)
                {
                    ddlGeneralPriority.SelectedValue = purchaseGeneralDS.Tables[0].Rows[0]["Priority"].ToString();
                    txtGeneralActualLeadDate.Text = purchaseGeneralDS.Tables[0].Rows[0]["PR_ActualLeadTime"].ToString();
                    txtGeneralExpectedLeadDate.Text = purchaseGeneralDS.Tables[0].Rows[0]["PR_ExpectedLeadTime"].ToString();
                    txtGeneralPurchaseRemarks.Text = purchaseGeneralDS.Tables[0].Rows[0]["Remarks"].ToString();
                    ddlGeneralPriority.Enabled = false;
                    txtGeneralActualLeadDate.Enabled = false;
                    txtGeneralExpectedLeadDate.Enabled = false;
                    txtGeneralPurchaseRemarks.Enabled = false;
                }
                // btnViewPurchaseReq.Visible = false;
                DataSet purchasedItemDS = purchase.GetGeneralPurchasedDetailsByRequestId(uniqId);
                grvViewItemDetailsGeneral.DataSource = purchasedItemDS;
                grvViewItemDetailsGeneral.DataBind();

            }
            else
            {
                grvMaterialDetails.Enabled = false;
                // TitlePanel.Visible = false;
                btnProductionWiseSubmit.Visible = false;
                btnViewPurchaseOrder.Visible = false;
                btnNewProduction.Visible = false;
                btnViewPurchaseReq.Visible = false;
                GetProducts();
                TabContainer1.ActiveTabIndex = 0;
                TabContainer1.Tabs[1].HeaderText = string.Empty;

                TabContainer1.Tabs[0].HeaderText = string.Empty;
                TabContainer1.Tabs[1].CssClass = "InboxTableHeader";
                TabContainer1.Tabs[0].CssClass = "InboxTableHeader";
                TabPanel1.CssClass = "InboxTableHeader";
                TabPanel2.CssClass = "InboxTableHeader";

                //  TabContainer1.Enabled = false;
                //  btnViewPurchaseReq.Visible = false;
                Button6.Visible = false;
                btnSend.Visible = false;
                Button3.Visible = false;
                Button5.Visible = false;
                btnProductionUpdate.Visible = false;
                btnProductionSave.Visible = false;
                btnNewProduction.Visible = false;
                btnPrint.Visible = false;
                btnExportToPdf.Visible = false;
                DataSet purchaseDS = purchase.GetPurchaseMasterDetailsByRequestId(uniqId);
                if (purchaseDS.Tables[0].Rows.Count > 0)
                {
                    ddlProductName.SelectedValue = purchaseDS.Tables[0].Rows[0]["PR_ProductID"].ToString();
                    txtQty.Text = purchaseDS.Tables[0].Rows[0]["PR_ProductQuantity"].ToString();
                    txtActualLeadTime.Text = purchaseDS.Tables[0].Rows[0]["PR_ActualLeadTime"].ToString();
                    txtDueDate.Text = purchaseDS.Tables[0].Rows[0]["PR_ExpectedLeadTime"].ToString();
                    lblD1.Text = purchaseDS.Tables[0].Rows[0]["PR_DateTime"].ToString();
                    ddlPriority.SelectedValue = purchaseDS.Tables[0].Rows[0]["Priority"].ToString();
                    txtRemarks.Text = purchaseDS.Tables[0].Rows[0]["Remarks"].ToString();
                    txtRemarks.Enabled = false;
                    ddlPriority.Enabled = false;
                    ddlProductName.Enabled = false;
                    txtQty.Enabled = false;
                    txtActualLeadTime.Enabled = false;
                    txtDueDate.Enabled = false;
                    ImageToControl.Visible = false;
                    imbCalendar.Visible = false;
                    if (uniqId != 0)
                    {
                        grdSelectUniqId = uniqId;
                        int productId = Convert.ToInt16(ddlProductName.SelectedValue);
                        DataSet materialDS = purchase.GetPrchasedItemsByRequestId(uniqId);
                        grvMaterialDetails.DataSource = materialDS;
                        grvMaterialDetails.DataBind();
                    }
                }

            }

        }
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
       // Session["ctrl"] = Panel1;
     // Page.ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('BusinessProcessAutomation.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
    }
    /// <summary>
    /// Delete Item From GridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDeleteBomList_Click(object sender, EventArgs e)
    {
        string path = string.Empty;
        ImageButton btn = (ImageButton)sender;
        string requestUniqId = btn.CommandArgument;
        int uniqID=Convert.ToInt16(requestUniqId);
        bool status = purchase.DeleteBOMList(uniqID);
        if (status)
        {
            lblProductionWisePurchaseMessage.Visible = true;
            lblProductionWisePurchaseMessage.Text = "Deleted Successfully";
            GetProductionWisePurchasedItems();
        }
        else
        {
            lblProductionWisePurchaseMessage.Visible = true;
            lblProductionWisePurchaseMessage.Text = "Couldnt Delete Item From BOM List";
        }
    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (linkKey != 0)
        {
            SendRequest();
        }
        else
        {
            MessageBox.Show("Failed to Send the Request");
        }
    }
    protected void btnSendForApproval_Click(object sender, EventArgs e)
    {
        try
        {
            if (linkKey != 0)
            {
                int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
                Session["UserManager_Control"] = "Purchase/ucManuallySendForApproval.ascx";
                Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + System.Convert.ToInt32(linkKey) + "&RequestType=" + requestTypeId + "&RequestLinkId=" + requestListUniqRecordNumber);

            }
            else
            {
                MessageBox.Show("Failed to Forward the Purchase Request");
            }
        }
        catch (Exception ex)
        {
            errorLog.LogWriter(Server.MapPath("Logs/ErrorLog"), ex.Message);
        }
       
    }
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grvViewPurchasedItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvViewPurchasedItems.PageIndex = e.NewPageIndex;
        GetProductionWisePurchasedItems();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
    {
        if (TabContainer1.ActiveTabIndex == 0)
        {
            requestType = 1;
            ProductionClearControls();
            btnNewProduction.Visible = true;
            ddlProductName.Enabled = true;
            txtQty.Enabled = true;
            txtDueDate.Enabled = true;
            txtActualLeadTime.Enabled = true;
            btnPrint.Visible = true;
            btnExportToPdf.Visible = true;
            Session["hasrequestLinkId"]  = null ;
            Session["requestTypeId"] = null;
        }
        else
        {

            requestType = 2;
            Button6.Visible = true;
            GeneralPurchaseRequestClearControls();
            Session["hasrequestLinkId"] = null;
            Session["requestTypeId"] = null;
            //btnProductionSave.Visible = false;
            //Button1.Visible = true;

        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("click");
    }
    protected void btnNewProduction_Click(object sender, EventArgs e)
    {
        ProductionClearControls();
    }
    protected void btnGeneralNewPurchaseRequest_Click(object sender, EventArgs e)
    {
        GeneralPurchaseRequestClearControls();
    }

    protected void ProductionClearControls()
    {
        cpnlExtender.Collapsed = true;
        grdSelectUniqId = 0;
        linkKey = 0;
        ddlProductName.SelectedIndex = 0;
        txtQty.Text = string.Empty;
        grvMaterialDetails.DataSource = null;
        grvMaterialDetails.DataBind();
        ddlPriority.SelectedIndex = 0;
        txtRemarks.Text = string.Empty;
        txtActualLeadTime.Text = DateTime.Now.ToString("MM/dd/yyyy");
        txtDueDate.Text = DateTime.Now.ToString("MM/dd/yyyy"); 
        btnUpdate.Visible = false;
        btnProductionUpdate.Visible = false;
        btnProductionSave.Visible = true;
        btnProductionWiseSubmit.Visible = true;
    }

    protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        if (grvViewPurchasedItems.SelectedIndex == -1)
        {
            MessageBox.Show("Please select an Item from the table RepeatOrder");
           // lblProductionWisePurchaseMessage.Visible = true;
           // lblProductionWisePurchaseMessage.Text = "Please select an Item ";

        }
        else
        {
            if (grdSelectUniqId != 0 && statusId==4)
            {
                CreatePDFDocument();

            }
            else
            {
                MessageBox.Show("Waiting to approve");

            }

        }
     

        //int pageNumber = 1;
        //PdfReader reader = new PdfReader("D:\\BindhyaChandran\\Documentation\\auto toilet lamp.pdf");
        ////System.Drawing.Rectangle  size = reader.GetPageSizeWithRotation(pageNumber);
        //Document document = new Document();
        //PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Document.pdf", FileMode.Create, FileAccess.Write));


       
        //document.AddSubject("Binzz");

        //document.Open();

        //PdfContentByte cb = writer.DirectContent;
        //document.NewPage();
        //PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
        //cb.AddTemplate(page, 0, 0);
        //document.Close();
    }

    protected void lbRemove_Click(object sender, EventArgs e)
    {
        int subAmt = 0;
        string amount = string.Empty;
        int grvCount = 0;
        LinkButton lb = (LinkButton)sender;
        GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
       // int rowID = gvRow.RowIndex + 1;
        int rowID = gvRow.RowIndex;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 1)
            {
                if (gvRow.RowIndex < dt.Rows.Count - 1)
                {
                    amount = dt.Rows[rowID][4].ToString();
                    if (amount != "")
                        subAmt = Convert.ToInt32(amount);

                    //Remove the Selected Row data
                    dt.Rows.Remove(dt.Rows[rowID]);
                }
                grvCount = dt.Rows.Count - 1;
            }
            //Store the current data in ViewState for future reference
            ViewState["CurrentTable"] = dt;
            //Re bind the GridView for the updated data
            gvItemDetails.DataSource = dt;
            gvItemDetails.DataBind();
            htmlHidden.Value = grvCount.ToString();
            if (grdTotalGeneral >= subAmt)
                grdTotalGeneral = grdTotalGeneral - subAmt;
        }
        
        //Set Previous Data on Postbacks
        SetPreviousData();
    }


    //public override void VerifyRenderingInServerForm(Control control)
    //{
    //    /* Verifies that the control is rendered */
    //}
    //public override void VerifyRenderingInServerForm(GridView grvViewPurchasedItems)
    //{

    //}
    /// <summary>
    /// Bind Materials By selecting Product
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlProductName_SelectedIndexChanged1(object sender, EventArgs e)
    {
        int productID  =0;
        grdSelectUniqId = 0;
        txtQty.Text = "1";
        if(ddlProductName.SelectedIndex!=0)
         productID = Convert.ToInt16(ddlProductName.SelectedValue);

        if (ddlProductName.SelectedIndex == 0)
        {
            grvMaterialDetails.DataSource = null;
            grvMaterialDetails.DataBind();
        }
        else
        {
            if (productID != 0)
            {
                DataSet materialDS = purchase.GetMaterialDetailsByProductID(productID);
                grvMaterialDetails.DataSource = materialDS;
                grvMaterialDetails.DataBind();                
            }
        }

     //   txtQty.Text = "1";
    }

    protected void ddlItmName_SelectedIndexChanged(object sender, EventArgs e)
    {
       
        
    }

    protected void grvViewPurchasedItems_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlProductName.Enabled=false;
        btnSend.Visible = false;
        btnSendForApproval.Visible = false;
        btnProductionSave.Visible = false;
        btnViewPurchaseReq.Visible = true;
        btnViewPurchaseOrder.Visible = true;
        btnProductionWiseSubmit.Visible = false;
        btnUpdate.Visible = true;
        btnProductionUpdate.Visible = true;
        cpnlExtender.Collapsed = false;
        btnProductionSubmit.Visible = true;

        GridViewRow row = grvViewPurchasedItems.SelectedRow;
        string lbluniqId = ((Label)row.FindControl("lblUniqID")).Text;
        int purchaseRequestID = Convert.ToInt16(lbluniqId);
        grdSelectUniqId = purchaseRequestID;
        linkKey = grdSelectUniqId;
        ddlProductName.SelectedValue = ((Label)row.FindControl("lblProductID")).Text;
        txtQty.Text = ((Label)row.FindControl("lblQty")).Text;
        txtDueDate.Text = ((Label)row.FindControl("lblDate")).Text;
        txtActualLeadTime.Text = ((Label)row.FindControl("lblActualDate")).Text;

        requestLinkUniqID =((Label)row.FindControl("lblRequestLinkUniqID")).Text;
        if (requestLinkUniqID != "")
            requestLinkUID = Convert.ToInt16(requestLinkUniqID);
        string statusNo = ((Label)row.FindControl("lblStatusId")).Text; 
        if (statusNo != "")
            statusId = Convert.ToInt16(statusNo);

        if (purchaseRequestID != 0)
        {
            int productId = Convert.ToInt16(ddlProductName.SelectedValue);
            DataSet purchaseDS = purchase.GetPrchasedItemsByRequestId(purchaseRequestID);
            grvMaterialDetails.DataSource = purchaseDS;
            grvMaterialDetails.DataBind();
        }
    }
    protected void btnGeneralForward_Click(object sender, EventArgs e)
    {
        int userId=0;
        if (Session["UserId"] != null)
            userId = Convert.ToInt16(Session["UserId"].ToString());
        else
            userId = 10;
        int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
        //requestCreate.CreateRequest("PurchaseRequest",0, generalPurchaseUniqId);
        //bool status2 = purchase.UpdatePurchaseRequestStatus(generalPurchaseUniqId, 2);
        int inboxUniqId = inBoxCreate.CreateInBox(requestTypeId, userId, generalPurchaseUniqId);
        bool status = inBoxCreate.UpdateInBoxStatus(inboxUniqId, userId, 1, txtGeneralPurchaseRemarks.Text);
        if (status)
        {
            lblErrMessage.Text = "Forwarded Purchase Request Successfully";
            btnGeneralForward.Visible = false;
            btnGeneralSendForApproval.Visible = false;
            Button1.Visible = false;
            Button2.Visible = false;


        }
        else
        {
            lblErrMessage.Text = "Failed to Forward.Please try again..";
        }
        
    }
    protected void btnGeneralSendForApproval_Click(object sender, EventArgs e)
    {
        Button1.Visible = false;
        Button2.Visible = false;

       // requestCreate.CreateRequest("PurchaseRequest", 0, generalPurchaseUniqId);
        int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
        Session["UserManager_Control"] = "Purchase/ucManuallySendForApproval.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + generalPurchaseUniqId + "&RequestType=" + requestTypeId+"&RequestLinkId="+requestListUniqRecordNumber);

    }
    protected void btnProductionSubmit_Click(object sender, EventArgs e)
    {
        bool status;
        status = purchase.UpdateStepStatus(1, 2, requestListUniqRecordNumber);
        if (status)
        {
            MessageBox.Show("Successfully Submitted ..");
            btnProductionSubmit1.Visible = false;
            btnProductionSubmit1.Visible = false;
            btnSend.Visible = false;
            btnSendForApproval.Visible = true;
            btnUpdate.Visible = false;
            btnProductionUpdate.Visible = false;
        }
        else
            MessageBox.Show("Failed to Submit ");
    }
    protected void btnGeneralPurchaseSubmit_Click(object sender, EventArgs e)
    {
        bool status;
        status = purchase.UpdateStepStatus(1, 2, requestListUniqRecordNumber);
        if (status)
        {
            MessageBox.Show("Successfully Submitted ..");
            btnGeneralPurchaseSubmit.Visible = false;
            btnGeneralPurchaseSubmit1.Visible = false;
            btnGeneralSendForApproval.Visible = true;
            btnGeneralPurchaseSubmit.Visible = false;
            Button1.Visible = true;
            btnGeneralPurchaseRequestUpdate.Visible = false;
            Button5.Visible = false;
        }
        else
            MessageBox.Show("Failed to Submit ");
    }
    
    protected void btnGeneralPurchaseCompletede_Click(object sender, EventArgs e)
    {
        int priority=0;

        if(ddlGeneralPriority.SelectedIndex != 0)
            priority=Convert.ToInt16(ddlGeneralPriority.SelectedValue);
        else
            priority=0;
        object uniqIdentity = purchase.InsertProductionWisePurchaseMasterTable(requestType, grdTotalGeneral, txtGeneralExpectedLeadDate.Text, txtGeneralActualLeadDate.Text, Convert.ToInt16(null), Convert.ToInt16(null), priority, txtGeneralPurchaseRemarks.Text);
        int RequestId = Convert.ToInt16(uniqIdentity);
        generalPurchaseUniqId = RequestId;
        if (RequestId != 0)
        {
            int requesterId = 0;
            if(Session["UserId"] !=null)
                requesterId=Convert.ToInt16(Session["UserId"].ToString());
            InsertGeneralPurchase(RequestId);
            int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
            int requestListUniqId= requestCreate.CreateRequest("PurchaseRequest", 0, generalPurchaseUniqId);
            requestListUniqRecordNumber = requestListUniqId;
            bool status = purchase.UpdateReQuestStatus(generalPurchaseUniqId, requestTypeId, requesterId);
            GetGeneralPurchasedItems();

            gvItemDetails.DataSource = null;
            gvItemDetails.DataBind();
            gvItemDetails.Visible = false;
            grvViewItemDetailsGeneral.Visible = true;
            DataSet purchasedItemDS = purchase.GetGeneralPurchasedDetailsByRequestId(RequestId);
            grvViewItemDetailsGeneral.DataSource = purchasedItemDS;
            grvViewItemDetailsGeneral.DataBind();

            MessageBox.Show("Successfully Saved");
            //Apply stylesheet for gridview 
            Stylesheet.Attributes.Add("href", "../../Css/SkylineFair.css");
            Stylesheet.Attributes.Add("type", "text/css");
            Stylesheet.Attributes.Add("rel", "stylesheet");
            TabContainer1.CssClass = "blue";
            gvItemDetails.CssClass = "grid-view";

            btnGeneralForward.Visible = false;
            btnGeneralSendForApproval.Visible = false;
            btnGeneralPurchaseSubmit.Visible = true;
            btnGeneralPurchaseSubmit1.Visible = true;
            Button1.Visible = false;
            Button2.Visible = false;
            btnGeneralPurchaseCompleted.Visible = false;
            btnGeneralPurchaseRequestUpdate.Visible = true;
            Button3.Visible = false;
            Button5.Visible = true;
        }

    }
    protected void btnEditGeneralPurchase_Click(object sender, EventArgs e)
    {
        btnGeneralForward.Visible = false;
        btnGeneralSendForApproval.Visible = false;
        btnGeneralPurchaseSubmit1.Visible = true;
        btnGeneralPurchaseSubmit.Visible = true;
        generalPurchaseUniqId = 0;
        gvItemDetails.DataSource = null;
        gvItemDetails.DataBind();
        gvItemDetails.Visible = false;
        btnGeneralPurchaseCompleted.Visible = false;
        btnGeneralPurchaseRequestUpdate.Visible = true;
        Button3.Visible = false;
        Button5.Visible = true;
        grvViewItemDetailsGeneral.Visible = true;
        string path = string.Empty;
        ImageButton btn = (ImageButton)sender;
        string[] CommandArgument = btn.CommandArgument.Split(',');
        string requestNo = CommandArgument[0];
        string statusNo = CommandArgument[1];
        string requestlinkrecNo = CommandArgument[2];
        string priority = CommandArgument[3];
        if (priority != "")
            ddlGeneralPriority.SelectedValue =priority;
        if (requestlinkrecNo != "")
            requestListUniqRecordNumber = Convert.ToInt16(requestlinkrecNo);
        int requestId = Convert.ToInt16(requestNo);
        statusId = Convert.ToInt16(statusNo);
        grdselectGeneralUniqId = requestId;
        generalPurchaseUniqId = grdselectGeneralUniqId;
        DataSet purchasedItemDS = purchase.GetGeneralPurchasedDetailsByRequestId(requestId);
        grvViewItemDetailsGeneral.DataSource = purchasedItemDS;
        grvViewItemDetailsGeneral.DataBind();
    }
  

    protected void btnGeneralPurchaseRequestUpdate_Click(object sender, EventArgs e)
    {
        int priority = 0;
        if (ddlGeneralPriority.SelectedIndex != 0)
            priority = Convert.ToInt16(ddlGeneralPriority.SelectedValue);
        else
            priority = 0;
        if (generalPurchaseUniqId != 0)
        {
            purchase.UpdateProductionWisePurchaseRequestMaster(requestType, grdTotalGeneral, txtGeneralExpectedLeadDate.Text, txtGeneralActualLeadDate.Text, 0, 0, generalPurchaseUniqId,priority);
            UpdateGeneralPurchase();
            GetGeneralPurchasedItems();
            MessageBox.Show("Sucessfully Updated");
            //lblErrMessage.Visible = true;
            //lblErrMessage.Text = "Successfully Updated";
            btnGeneralForward.Visible = false;
            btnGeneralSendForApproval.Visible = false;
            Button1.Visible = false;
            Button2.Visible = false;
            btnGeneralPurchaseCompleted.Visible = false;
            Button3.Visible = false;

        }
        else if (grdselectGeneralUniqId!=0)
        {
            purchase.UpdateProductionWisePurchaseRequestMaster(requestType, grdTotalGeneral, txtGeneralExpectedLeadDate.Text, txtGeneralActualLeadDate.Text, 0, 0, grdselectGeneralUniqId,priority);
            UpdateGeneralPurchaseRequest();
            GetGeneralPurchasedItems();
            MessageBox.Show("Sucessfully Updated");
            //lblErrMessage.Visible = true;
            //lblErrMessage.Text = "Successfully Updated";
            btnGeneralForward.Visible = false;
            btnGeneralSendForApproval.Visible = false;
            Button1.Visible = false;
            Button2.Visible = false;
            btnGeneralPurchaseCompleted.Visible = false;
            Button3.Visible = false;
            DataSet purchasedItemDS = purchase.GetGeneralPurchasedDetailsByRequestId(grdselectGeneralUniqId);
            grvViewItemDetailsGeneral.DataSource = purchasedItemDS;
            grvViewItemDetailsGeneral.DataBind();


        }
        else
        {
            lblErrMessage.Visible = true;
            lblErrMessage.Text = "Failed to Update";
        }
    }

    protected void btnProductionSave_Click(object sender, EventArgs e)
    {
        int reqId = 0;
        if (Session["UserId"] != null)
            reqId = Convert.ToInt16(Session["UserId"].ToString());
        if (grvMaterialDetails.Rows.Count > 0)
        {
            InsertPurchaseMasterProductionWise();
            int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
            int uniqRequestLink= requestCreate.CreateRequest("PurchaseRequest", 0, linkKey);
            requestListUniqRecordNumber = uniqRequestLink;
            bool status = purchase.UpdateReQuestStatus(linkKey, requestTypeId, reqId);

           // ((TextBox)grvMaterialDetails.FooterRow.Cells[4].FindControl("txtGrantTotal")).Text = grdTotal.ToString();
           // lblProductionWisePurchaseMessage.Visible = true;
           // lblProductionWisePurchaseMessage.Text = "Saved Successfully";
            GetProductionWisePurchasedItems();
            MessageBox.Show("Saved Successfully");

       
            btnSend.Visible = false;
            btnSendForApproval.Visible = false;
            btnUpdate.Visible = true;
            btnProductionUpdate.Visible = true;
            btnProductionSubmit1.Visible = true;
            btnProductionSubmit.Visible = true;

        }
        else
        {
            lblProductionWisePurchaseMessage.Text = "Plz select!!!";
        }

    }
    protected void btnProductionUpdate_Click(object sender, EventArgs e)
    {
        int reqId = 0;
        if (Session["UserId"] != null)
            reqId = Convert.ToInt16(Session["UserId"].ToString());

            if (grvViewPurchasedItems.SelectedIndex > -1)
            {
                UpdatePurchaseMasterProductionWise();
               // GetProductionWisePurchasedItems();
              //  ClearControls();
              //  btnProductionSubmit.Visible = true;
               // btnProductionSubmit1.Visible = true;

               // int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
               // int uniqRequestLink = requestCreate.CreateRequest("PurchaseRequest", 0, linkKey);
                requestListUniqRecordNumber = requestLinkUID;
               // bool status = purchase.UpdateReQuestStatus(linkKey, requestTypeId, reqId);

                MessageBox.Show("Successfully Updated");
            }
            else if (Request.QueryString["linkKey"].ToString() != null && Request.QueryString["RequestType"].ToString() == "1" && Request.QueryString["ReqUID"].ToString()!=null)
            {
                int reqUniqID = 0;
                linkKey = Convert.ToInt32(Request.QueryString["linkKey"].ToString());
                reqUniqID = Convert.ToInt32(Request.QueryString["ReqUID"].ToString());
                UpdatePurchaseMasterProductionWise();
                requestListUniqRecordNumber = reqUniqID;
                //int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
                //int uniqRequestLink = requestCreate.CreateRequest("PurchaseRequest", 0, linkKey);
                //requestListUniqRecordNumber = uniqRequestLink;
                //bool status = purchase.UpdateReQuestStatus(linkKey, requestTypeId, reqId);

                //GetProductionWisePurchasedItems();
                //ClearControls();
                MessageBox.Show("Successfully Updated");
            }

            else
            {
                MessageBox.Show("Cant Updated");
            }
       
    }
    protected void btnViewPurchaseReq_Click(object sender, EventArgs e)
    {
        Session["UserManager_Control"] = "Purchase/SerchPyrchaseRequest.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx?reqType=" + requestType);
      //  Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + System.Convert.ToInt32(linkKey) + "&RequestType=" + requestTypeId);

    }
    

    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }
    protected void grvViewItemDetailsGeneral_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        double amt = 0;

        double amount = 0;
        foreach (GridViewRow gvr in grvViewItemDetailsGeneral.Rows)
        {


            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice1");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtRequiredQty1"); //get the quantity TextBox
            TextBox tbTotal = (TextBox)gvr.Cells[3].FindControl("txtTotal2");


            int totQty = Convert.ToInt16(tbQty.Text);
            amount = Convert.ToDouble(price1 * totQty);


            tbTotal.Text = amount.ToString("c").Replace("$", "Rs "); 
            grdTotal = amount + amt;
            amt = grdTotal;
            grdTotalGeneral = grdTotal;

        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[3].Text = "Total Amount:";
            e.Row.Cells[4].Text = grdTotal.ToString("c").Replace("$", "Rs "); 
            grdTotalGeneral = grdTotal;
            //e.Row.Cells[0].Text = "Total";
            //e.Row.Cells[1].Text = string.Format("{0:c}", grdTotal);
        }

    }
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 

    protected void grvMaterialDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               // grvMaterialDetails.Columns[3].Visible = false;
                int materialId = 0;
                string lblUnit = ((Label)e.Row.FindControl("lblMaterialId")).Text;
                if (lblUnit != "")
                    materialId = Convert.ToInt16(lblUnit);

                DataSet vendorDS = purchase.GetVendorDetails(materialId);
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddlVendorName");
                ddl.DataSource = vendorDS;
                ddl.DataValueField = "VendorID";
                ddl.DataTextField = "VR_VendorName";
                ddl.DataBind();
              //  ddl.Items.Insert(0, "-Select-");
            }
            if (grdSelectUniqId > 0)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                
                        int vendorId = 0;
                        int materialId = 0;
                        string lblUnit = ((Label)e.Row.FindControl("lblMaterialId")).Text;
                        if (lblUnit != "")
                            materialId = Convert.ToInt16(lblUnit);
                        DropDownList ddl = (DropDownList)e.Row.FindControl("ddlVendorName");
                        vendorId = purchase.GetVendorNameByMaterialIDAndRequestId(grdSelectUniqId, materialId);
                        ddl.SelectedValue = vendorId.ToString();
                        //grvMaterialDetails.Columns[3].Visible = true;

                }
            }
                
            // }
            // }

        
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";

        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
       

        double amt = 0;
      //  double totalAmt = 0;
        //if (e.Row.RowType == DataControlRowType.Header)
        //{
        //    totalAmt = 0;
        //}
        int uQty =0;
        double amount = 0;
        int qty = 0;
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {
            

            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTotal"); //get the total TextBox
            Label lblUnit = (Label)gvr.Cells[1].FindControl("lblUnit");

            
            int totQty = Convert.ToInt16(txtQty.Text);
            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{
            qty = Convert.ToInt16(tbQty.Text);
            if (lblUnit.Text != "")
                uQty = Convert.ToInt16(lblUnit.Text);
            else
                uQty = 0;
            tbQty.Text = Convert.ToString(uQty * totQty);

            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{
            qty = Convert.ToInt16(tbQty.Text);
            amount = price1 * qty;
            //}
            tbTotal.Text = amount.ToString("c").Replace("$", "Rs "); 
            grdTotal = amount + amt;
            amt = grdTotal;

        }
        //foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        //{
        //    // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
        //    TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
        //    double price1 = Convert.ToDouble(price.Text);
        //    TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
        //    TextBox tbTotal = (TextBox)gvr.Cells[4].FindControl("txtTotal"); //get the total TextBox
        //    Label lblUnit = (Label)gvr.Cells[1].FindControl("lblUnit"); 

        //    int totQty = Convert.ToInt16(txtQty.Text);
        //    //if (int.TryParse(tbQty.Text.Trim(), out qty))
        //    //{
        //    qty = Convert.ToInt16(tbQty.Text);
        //    if (lblUnit.Text != "")
        //        uQty = Convert.ToInt16(lblUnit.Text);
        //    else
        //        uQty = 0;
        //    tbQty.Text = Convert.ToString(uQty * totQty);
        //    amount = price1 * qty;
        //    //}
        //    tbTotal.Text = amount.ToString("C2");
        //    grdTotal = amount + amt;
        //    amt = grdTotal;

        //}
       // if (grdTotal != 0)
            // ((TextBox)grvMaterialDetails.FooterRow.Cells[4].FindControl("txtGrantTotal")).Text = grdTotal.ToString();

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[6].Text = "Total Amount:";
                e.Row.Cells[7].Text = grdTotal.ToString("c").Replace("$", "Rs "); 
                expectedAmount = grdTotal;
                //e.Row.Cells[0].Text = "Total";
                //e.Row.Cells[1].Text = string.Format("{0:c}", grdTotal);
            }
        //if (e.Row.RowType == DataControlRowType.Footer)
        //{
        //    var amountTotalLabel = (TextBox)e.Row.FindControl("txtGrantTotal");
        //    amountTotalLabel.Text = totalAmt.ToString("0.00");
        //}


        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{

        //    TextBox txtQuantity = (TextBox)e.Row.Cells[2].FindControl("txtQuantity");

        //    TextBox txtUnitPrice = (TextBox)e.Row.Cells[3].FindControl("txtUnitPrice");

        //    TextBox txtTotal = (TextBox)e.Row.Cells[4].FindControl("txtTotal");

        //    txtQuantity.Attributes.Add("onkeypress", "javascript:Multiply('" + txtQuantity.ClientID.ToString() + "','" + txtUnitPrice.ClientID.ToString() + "','" + txtTotal.ClientID.ToString() + "')");
        //}
    }
    protected void InsertGeneralPurchase(int requestId)
    {
        if (gvItemDetails.Rows.Count > 0)
        {
            lblErrMessage.Text = "";
          //  lblErrMessage.Visible = false;
            foreach (GridViewRow gvr in gvItemDetails.Rows)
            {
                TextBox txtProduct = (TextBox)gvr.Cells[1].FindControl("txtProduct");
                TextBox txtSpecification = (TextBox)gvr.Cells[2].FindControl("txtSpecification");
                TextBox txtUnitPrice = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
                TextBox txtRequiredQty = (TextBox)gvr.Cells[4].FindControl("txtRequiredQty");
                bool status = purchase.InsertGeneralPurchaseRequest(requestId, txtProduct.Text, Convert.ToInt16(txtRequiredQty.Text), Convert.ToDouble(txtUnitPrice.Text), txtSpecification.Text);
            }
        }
        else
        {
            lblErrMessage.Visible = true;
            lblErrMessage.Text = "Please Enter ProductDetails";
        }
        //  bool status=purchase.InsertGeneralPurchaseRequest(RequestId,txtge

    }

    protected void UpdateGeneralPurchase()
    {
        if (generalPurchaseUniqId!=0)
        {
            int uniqId=0;
            if (grvViewItemDetailsGeneral.Rows.Count > 0)
            {
                foreach (GridViewRow gvr in grvViewItemDetailsGeneral.Rows)
                {
                    Label lblid = (Label)gvr.Cells[1].FindControl("lblUniq");
                    
                    TextBox txtProduct = (TextBox)gvr.Cells[1].FindControl("txtProduct1");
                    TextBox txtSpecification = (TextBox)gvr.Cells[2].FindControl("txtSpecification1");
                    TextBox txtUnitPrice = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice1");
                    TextBox txtRequiredQty = (TextBox)gvr.Cells[4].FindControl("txtRequiredQty1");
                    if (lblid.Text != "")
                        uniqId = Convert.ToInt16(lblid.Text);
                    bool status = purchase.UpdateGeneralPurchaseRequest(generalPurchaseUniqId, txtProduct.Text, Convert.ToInt16(txtRequiredQty.Text), Convert.ToDouble(txtUnitPrice.Text), txtSpecification.Text, uniqId);
                }
            }

        }
        else
        {
            lblErrMessage.Visible = true;
            lblErrMessage.Text="Failed to update";
        }
    }
    protected void UpdateGeneralPurchaseRequest()
    {
        if (grdselectGeneralUniqId != 0)
        {
            if (grvViewItemDetailsGeneral.Rows.Count > 0)
            {
                int uniqId=0;
                foreach (GridViewRow gvr in grvViewItemDetailsGeneral.Rows)
                {
                   TextBox txtUniqId = (TextBox)gvr.Cells[1].FindControl("txtUniqId");

                    TextBox txtProduct = (TextBox)gvr.Cells[0].FindControl("txtProduct1");
                    TextBox txtSpecification = (TextBox)gvr.Cells[0].FindControl("txtSpecification1");
                    TextBox txtUnitPrice = (TextBox)gvr.Cells[2].FindControl("txtUnitPrice1");
                    TextBox txtRequiredQty = (TextBox)gvr.Cells[3].FindControl("txtRequiredQty1");
                    if(txtUniqId.Text!="")
                        uniqId=Convert.ToInt16(txtUniqId.Text);
                    bool status = purchase.UpdateGeneralPurchaseRequest(grdselectGeneralUniqId, txtProduct.Text, Convert.ToInt16(txtRequiredQty.Text), Convert.ToDouble(txtUnitPrice.Text), txtSpecification.Text, uniqId);
                }
            }
        }
        else
        {
            lblErrMessage.Visible = true;
            lblErrMessage.Text = "Failed to update";
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {

        FindProductionWiseTotalAmount();

    }

    protected void  FindTotalAmountWithGeneralPurchase()
    {
        double amt = 0;
        foreach (GridViewRow gvr in gvItemDetails.Rows)
        {
            TextBox tbQty = (TextBox)gvr.Cells[4].FindControl("txtRequiredQty");
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTP");
            int totQty = Convert.ToInt16(tbQty.Text);

            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price

            tbTotal.Text = Convert.ToString(price1 * totQty);

            grdTotalGeneral = Convert.ToDouble(tbTotal.Text) + amt;
            amt = grdTotalGeneral;
            //amount = price1 * qty;
            ////}
            //tbTotal.Text = amount.ToString("C2");
            //grdTotal = amount + amt;
            //amt = grdTotal;

        }
        htmlHidden.Value = "1";
       // decimal.Parse(((TextBox)gvItemDetails.FooterRow.FindControl("PriceTextBox")).Text);
      //  TextBox t = (TextBox)gvItemDetails.FooterRow.Cells[5].FindControl("txtGrantTot");
      //  ro.Cells[4].Text = grdTotal.ToString("c").Replace("$", "Rs "); 

        ((TextBox)gvItemDetails.FooterRow.FindControl("txtGrantTot")).Text = grdTotalGeneral.ToString("c").Replace("$", "Rs "); 
    }
    protected void txtUnitPrice1_TextChanged(object sender, EventArgs e)
    {
     }
    
    protected void txtRequiredQty_TextChanged(object sender, EventArgs e)
    {
            FindTotalAmountWithGeneralPurchase();

    }
    
    protected void txtQty_TextChanged(object sender, EventArgs e)
    {
         if(grvMaterialDetails.Rows.Count>0)
        FindTotalAmount();
    }
    protected void txtRequiredQty1_TextChanged(object sender, EventArgs e)
    {
        if (grvViewItemDetailsGeneral.Rows.Count > 0)
        {
            double amt = 0;

            double amount = 0;
            foreach (GridViewRow gvr in grvViewItemDetailsGeneral.Rows)
            {


                // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
                TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice1");
                double price1 = Convert.ToDouble(price.Text);
                TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtRequiredQty1"); //get the quantity TextBox
                TextBox tbTotal = (TextBox)gvr.Cells[3].FindControl("txtTotal2");


                int totQty = Convert.ToInt16(tbQty.Text);
                amount = Convert.ToDouble(price1 * totQty);


                tbTotal.Text = amount.ToString("c").Replace("$", "Rs "); 
                grdTotal = amount + amt;
                amt = grdTotal;
                grdTotalGeneral = grdTotal;
            }
            if (grdTotal != 0 )
            {
                GridViewRow ro = grvMaterialDetails.FooterRow;
                ro.Cells[3].Text = "Total";
                ro.Cells[4].Text = grdTotal.ToString("c").Replace("$", "Rs "); 

               // ((TextBox)grvViewItemDetailsGeneral.FooterRow.FindControl("txtGrantTotal2")).Visible = true;
              //  ((TextBox)grvViewItemDetailsGeneral.FooterRow.FindControl("txtGrantTotal2")).Text = grdTotal.ToString("C2");
                grdTotalGeneral = grdTotal;
            }
        }
           
    }
    protected void grvViewGeneralPurchasedItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
         if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // statusId = 0;
            //string statusNo = ((Label)e.Row.FindControl("lblStatusId")).Text;
            //if (statusNo != "")
            //    statusId = Convert.ToInt16(statusNo);

   
            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
    }
  
    protected void grvViewPurchasedItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // statusId = 0;
            //string statusNo = ((Label)e.Row.FindControl("lblStatusId")).Text;
            //if (statusNo != "")
            //    statusId = Convert.ToInt16(statusNo);

   
            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
    }
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      //  FindTotalAmountWithGeneralPurchase();
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            LinkButton lb = (LinkButton)e.Row.FindControl("lbRemove");
            if (lb != null)
            {
                if (dt.Rows.Count > 1)
                {
                    if (e.Row.RowIndex == dt.Rows.Count - 1)
                    {
                        lb.Visible = false;
                    }
                }
                else
                {
                    lb.Visible = false;
                }
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[4].Text = "Total:";
        }
    }

   
   
    #endregion

    #region Methods


    /// <summary>
    /// 
    /// </summary>
    protected void GetProductionWisePurchasedItems()
    {
        int userId = 0;
        if (Session["UserId"] != null)
            userId = Convert.ToInt16(Session["UserId"].ToString());
        DataSet purchaseDS = purchase.GetProductionWisePurchasedItems(userId);
        grvViewPurchasedItems.DataSource = purchaseDS;
        grvViewPurchasedItems.DataBind();
    }
    protected void GetGeneralPurchasedItems()
    {
        int userId=0;
        if(Session["UserId"] !=null)
           userId=Convert.ToInt16(Session["UserId"].ToString());
        DataSet purchaseDS = purchase.GetGeneralPurchasedItems(userId);
        grvViewGeneralPurchasedItems.DataSource = purchaseDS;
        grvViewGeneralPurchasedItems.DataBind();
    }

  
    /// <summary>
    /// 
    /// </summary>
    protected void GetProducts()
    {
        DataSet purchaseDS = purchase.GetProducts();
        ddlProductName.DataSource = purchaseDS;
        ddlProductName.DataValueField = "ProductID";
        ddlProductName.DataTextField = "ProductName";
        ddlProductName.DataBind();
        ddlProductName.Items.Insert(0, "-Select-");

        //ddlProductCategory.DataSource = purchaseDS;
        //ddlProductCategory.DataValueField = "PD_ProductID";
        //ddlProductCategory.DataTextField = "PD_ProductName";
        //ddlProductCategory.DataBind();
        //ddlProductCategory.Items.Insert(0, "-Select-");


    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="_price"></param>
    private void CalcTotal(double _price)
    {
        try
        {
            runningTotal += _price;
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.ToString());
        }
    }

    /// <summary>
    /// Create First row in Gridview
    /// </summary>
   

    /// <summary>
    /// Populate Available Materials in ComboBox
    /// </summary>
    private void GetMaterials()
    {
        //DataSet materialsDS = purchase.GetMaterials();
      
        //    // Nested DropDownList Control reference is passed to the DrdList object. This will allow you access the properties of dropdownlist placed inside the GridView Template column.

        //    // DataBinding of nested DropDownList Control for each row of GridView Control.
        //    ddlMaterialName.DataSource = materialsDS;
        //    ddlMaterialName.DataValueField = "ML_MaterialID";
        //    ddlMaterialName.DataTextField = "ML_Name";
        //    ddlMaterialName.DataBind();
        //    ddlMaterialName.Items.Insert(0, "-Select-");
        //    int count = ddlMaterialName.Items.Count;
        //    ddlMaterialName.Items.Insert(count, new ListItem("Other"));
        //    // drdList.SelectedIndex = drdList.Items.Count + 1;
        //    ddlMaterialName.SelectedIndex = -1;
        // DropDownList tbTotal = (DropDownList)gvItemDetails.Cells[1].FindControl("ddlItmName");
        // tbTotal.Items.Add("Other");
    }

    private void GetPriority()
    {

        DataSet priorityDS = purchase.GetPriority();
        ddlGeneralPriority.DataSource = priorityDS;
        ddlGeneralPriority.DataValueField = "PriorityId";
        ddlGeneralPriority.DataTextField = "Priority";
        ddlGeneralPriority.DataBind();
        ddlGeneralPriority.Items.Insert(0, "-Select-");


        ddlPriority.DataSource = priorityDS;
        ddlPriority.DataValueField = "PriorityId";
        ddlPriority.DataTextField = "Priority";
        ddlPriority.DataBind();
        ddlPriority.Items.Insert(0, "-Select-");
       // ddlPriority.SelectedIndex = -1;

        
    }

    private void SetInitialRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        dt.Columns.Add(new DataColumn("Column4", typeof(string)));
        dt.Columns.Add(new DataColumn("Column5", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dr["Column3"] = string.Empty;
        dr["Column4"] = string.Empty;
        dr["Column5"] = string.Empty;
        dt.Rows.Add(dr);
        //Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;
        gvItemDetails.DataSource = dt;
        gvItemDetails.DataBind();
        htmlHidden.Value = "0";
    }
    private void AddNewRowToGrid()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    // DropDownList box1 = (DropDownList)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("ddlItemName");
                    TextBox box1 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtProduct");
                    TextBox box2 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtRequiredQty");
                    TextBox box3 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtUnitPrice");
                    TextBox box4 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtTP");
                    TextBox box5 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtSpecification");

                    

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    if (box1.Text.Trim() != "" && box2.Text.Trim()!="")
                    {
                        lblErrMessage.Visible = false;
                        lblErrMessage.Text = "";
                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
                        //  itemIndex = Convert.ToInt16(box1.SelectedValue);
                        rowIndex++;
                    }
                    else
                    {
                        lblErrMessage.Visible = true;
                        lblErrMessage.Text = "Please Fill all Fields";
                        return;
                    }
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                gvItemDetails.DataSource = dtCurrentTable;
                gvItemDetails.DataBind();
                htmlHidden.Value = gvItemDetails.Rows.Count.ToString();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                GetMaterials();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    // DropDownList box1 = (DropDownList)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("ddlItemName");
                    TextBox box1 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[1].FindControl("txtProduct");
                    TextBox box2 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[4].FindControl("txtRequiredQty");
                    TextBox box3 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[3].FindControl("txtUnitPrice");
                    TextBox box4 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[5].FindControl("txtTP");
                    TextBox box5 = (TextBox)gvItemDetails.Rows[rowIndex].Cells[2].FindControl("txtSpecification");
                    TextBox box6 = (TextBox)gvItemDetails.FooterRow.FindControl("txtGrantTot");
                    if (i < dt.Rows.Count - 1)
                    {
                        //   box1.ClearSelection();
                        //   box1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
                        box1.Text = dt.Rows[i]["Column1"].ToString();
                        box2.Text = dt.Rows[i]["Column2"].ToString();
                        box3.Text = dt.Rows[i]["Column3"].ToString();
                        box4.Text = dt.Rows[i]["Column4"].ToString();
                        box5.Text = dt.Rows[i]["Column5"].ToString();
                        box6.Text = grdTotalGeneral.ToString("c").Replace("$", "Rs "); 
                    }


                    rowIndex++;
                }
            }
        }
    }

    protected void InsertPurchaseMasterGeneral()
    {

    }
    protected void InsertPurchaseMasterProductionWise()
    {

        int priority = 0;
        if (ddlPriority.SelectedIndex != 0)
        {
            priority = Convert.ToInt16(ddlPriority.SelectedValue);
        }
        else
        {
            priority = 0;
        }
        //type/getdae,amt,expdate,acdate
        object identity = purchase.InsertProductionWisePurchaseMasterTable(requestType, expectedAmount, txtDueDate.Text, txtActualLeadTime.Text, Convert.ToInt16(ddlProductName.SelectedValue), Convert.ToInt16(txtQty.Text),priority,txtRemarks.Text);
        purchaseRequestUniqId = Convert.ToInt16(identity);
        linkKey = purchaseRequestUniqId;
        if (purchaseRequestUniqId != 0)
        {
            InsertBOMList();
           // requestCreate.CreateRequest("PurchaseRequest", a, purchaseRequestUniqId);
            //InsertProductionWisePurchaseRequest();
        }

    }
    protected void UpdateProductionWisePurchaseRequest()
    {
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {
            int vendor;
            int materialId = 0;
            int requiredQty = 0;
            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            Label lblMaterialId = (Label)gvr.Cells[0].FindControl("lblMaterialId");
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            materialId = Convert.ToInt16(lblMaterialId.Text);
            requiredQty = Convert.ToInt16(tbQty.Text);
             DropDownList ddlVendorName = (DropDownList)gvr.Cells[2].FindControl("ddlVendorName"); //get the quantity TextBox
            if(ddlVendorName.SelectedIndex!=0)
                vendor=Convert.ToInt16(ddlVendorName.SelectedValue);
            else
                vendor=0;
            //(int materialId, int requestedQty, int priority, string remarks, int requesterId,  int requestID)
          //  bool status = purchase.InsertBOMList(purchaseRequestUniqId, Convert.ToInt16(ddlProductName.SelectedValue), materialId, requiredQty, vendor);


            bool status = purchase.UpdateBOMListByRequestId(grdSelectUniqId, Convert.ToInt16(ddlProductName.SelectedValue), materialId, requiredQty, vendor);
        }
        //  FindTotalAmount();
    }
    protected void UpdatePurchaseMasterProductionWise()
    {
        int priority = 0;
        if (ddlPriority.SelectedIndex != 0)
            priority = Convert.ToInt16(ddlPriority.SelectedValue);
        else
            priority = 0;
        if (grdSelectUniqId > 0)
        {
            purchase.UpdateProductionWisePurchaseRequestMaster(requestType, expectedAmount, txtDueDate.Text, txtActualLeadTime.Text, Convert.ToInt16(ddlProductName.SelectedValue), Convert.ToInt16(txtQty.Text), grdSelectUniqId,priority);
            UpdateProductionWisePurchaseRequest();
            btnProductionSubmit.Visible = true;
            btnProductionSubmit1.Visible = true;

        }

    }

    protected void InsertBOMList()
    {
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {
            int vendor=0;
            int materialId = 0;
            int requiredQty = 0;
            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            DropDownList ddlVendorName = (DropDownList)gvr.Cells[2].FindControl("ddlVendorName"); //get the quantity TextBox
                vendor=Convert.ToInt16(ddlVendorName.SelectedValue);

            Label lblMaterialId = (Label)gvr.Cells[0].FindControl("lblMaterialId");
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            materialId = Convert.ToInt16(lblMaterialId.Text);
            requiredQty = Convert.ToInt16(tbQty.Text);
            //(int materialId, int requestedQty, int priority, string remarks, int requesterId,  int requestID)
            bool status = purchase.InsertBOMList(purchaseRequestUniqId, Convert.ToInt16(ddlProductName.SelectedValue), materialId, requiredQty, vendor);
        } 
    }
    //protected void InsertProductionWisePurchaseRequest()
    //{
    //    foreach (GridViewRow gvr in grvMaterialDetails.Rows)
    //    {
    //        int materialId = 0;
    //        int requiredQty = 0;
    //        // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
    //        Label lblMaterialId = (Label)gvr.Cells[0].FindControl("lblMaterialId");
    //        TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
    //        materialId = Convert.ToInt16(lblMaterialId.Text);
    //        requiredQty = Convert.ToInt16(tbQty.Text);
    //                                             //(int materialId, int requestedQty, int priority, string remarks, int requesterId,  int requestID)
    //        bool status = purchase.InsertProductionWisePurchaseRequest(materialId, requiredQty, ddlPriority.SelectedIndex, txtRemarks.Text, 1, purchaseRequestUniqId);
    //    }
    //  //  FindTotalAmount();
    //}
  
    protected void FindTotalAmount()
    {
        // double netAmount = 0;
        double amt = 0;
        double amount = 0;
        int qty = 0;
        int uQty = 0;
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {
            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTotal"); //get the total TextBox
            Label lblUnit = (Label)gvr.Cells[1].FindControl("lblUnit");

            int totQty = Convert.ToInt16(txtQty.Text);
            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{
            qty = Convert.ToInt16(tbQty.Text);
            if (lblUnit.Text != "")
                uQty = Convert.ToInt16(lblUnit.Text);
            else
                uQty = 0;
            tbQty.Text = Convert.ToString(uQty * totQty);

            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{
            qty = Convert.ToInt16(tbQty.Text);
            amount = price1 * qty;
            //}grdTotal.ToString("c").Replace("$", "Rs "); 
            tbTotal.Text = amount.ToString("C2").Replace("$", "Rs "); 
            grdTotal = amount + amt;
            amt = grdTotal;

        }
        if (grdTotal != 0 && Session["hasrequestLinkId"] == null)
        {
            ((TextBox)grvMaterialDetails.FooterRow.FindControl("txtGrantTotal")).Visible = true;
            ((TextBox)grvMaterialDetails.FooterRow.FindControl("txtGrantTotal")).Text = grdTotal.ToString("c").Replace("$", "Rs "); 
        }
        else if(grdTotal>0)
        {
            GridViewRow ro = grvMaterialDetails.FooterRow;
            ro.Cells[6].Text = "Total";
            ro.Cells[7].Text = grdTotal.ToString("c").Replace("$", "Rs "); 
          //  grdTotalGeneral.ToString("c").Replace("$", "Rs"); 
          //  TextBox txtDateMod = (TextBox)grvMaterialDetails.FooterRow.FindControl("txtGrantTotal");
          //  txtDateMod.Text = grdTotal.ToString();
        }

            //  ((TextBox)grvMaterialDetails.FooterRow.Cells[5].FindControl("txtGrantTotal")).Text = "88";
            expectedAmount = grdTotal;
        //myDataSet.Tables[0].Compute("sum(unitsinstock)", "").ToString();
    }

    protected void FindProductionWiseTotalAmount()
    {
        // double netAmount = 0;
        double amt = 0;
        double amount = 0;
        int qty = 0;
        foreach (GridViewRow gvr in grvMaterialDetails.Rows)
        {
            // float price = float.Parse(gvr.Cells[3].Text.Trim()); //get the price
            TextBox price = (TextBox)gvr.Cells[3].FindControl("txtUnitPrice");
            double price1 = Convert.ToDouble(price.Text);
            TextBox tbQty = (TextBox)gvr.Cells[2].FindControl("txtQuantity"); //get the quantity TextBox
            TextBox tbTotal = (TextBox)gvr.Cells[5].FindControl("txtTotal"); //get the total TextBox
            //Label lblUnit = (Label)gvr.Cells[1].FindControl("lblUnit");

            //if (int.TryParse(tbQty.Text.Trim(), out qty))
            //{

            qty = Convert.ToInt16(tbQty.Text);
            amount = price1 * qty;
            //}
            tbTotal.Text = amount.ToString("c").Replace("$", "Rs ");
            grdTotalGeneral1 = amount + amt;
            amt = grdTotalGeneral1;


        }
        ((TextBox)grvMaterialDetails.FooterRow.FindControl("txtGrantTotal")).Text = grdTotalGeneral1.ToString("c").Replace("$", "Rs "); 

        
    }


    public void CreatePDFDocument()
    {
        int vendorId;
        string vendorName = string.Empty;
        string vendorAddress = string.Empty;
        string vendorPhone = string.Empty;
        MemoryStream MStream = new MemoryStream();
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);
        PdfWriter writer = PdfWriter.GetInstance(document, MStream);


        Phrase footPhraseImg = new Phrase("Page: ", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));
        HeaderFooter footer = new HeaderFooter(footPhraseImg, true);
        footer.Border = iTextSharp.text.Rectangle.TOP_BORDER;
        footer.Alignment = Element.ALIGN_RIGHT;
        document.Footer = footer;

        document.Open();

        iTextSharp.text.Image imghead = iTextSharp.text.Image.GetInstance(Server.MapPath("~\\images\\ebirdlogo.jpg"));
        imghead.SetAbsolutePosition(0, 0);
        imghead.Alignment = Element.ALIGN_RIGHT;
        PdfContentByte cbhead = writer.DirectContent;
        PdfTemplate tp = cbhead.CreateTemplate(350, 393);
        tp.AddImage(imghead);
        cbhead.AddTemplate(tp, 30, 740);
        Phrase headPhraseImg = new Phrase(imghead + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 7, iTextSharp.text.Font.NORMAL));
        HeaderFooter header = new HeaderFooter(headPhraseImg, true);
        header.Alignment = Element.ALIGN_TOP;
        header.Border = iTextSharp.text.Rectangle.TOP_BORDER;

        int requestId = grdSelectUniqId;
        DataSet vendorDS = purchase.GetVendorByRequestId(requestId);
        for (int vendorCount = 0; vendorCount < vendorDS.Tables[0].Rows.Count; vendorCount++)
        {
           
            string vendor = vendorDS.Tables[0].Rows[vendorCount]["PreferedVendor"].ToString();
            if (vendor != "" || vendor != null)
            {

                vendorId = Convert.ToInt16(vendor);
            }
            else
            {
                vendorId = 0;
            }

            if (vendorId != 0)
            {
               DataSet  vendorDetailsDS = purchase.GetVendorDetailsById(vendorId);
               if (vendorDetailsDS.Tables[0].Rows.Count > 0 && vendorId != 0)
                {
                    vendorName = vendorDetailsDS.Tables[0].Rows[0]["VR_VendorName"].ToString();
                    vendorAddress = vendorDetailsDS.Tables[0].Rows[0]["VR_VendorAddress"].ToString();
                    vendorPhone = vendorDetailsDS.Tables[0].Rows[0]["VR_VendorPhone"].ToString();

                }

            }
            else
            {
                vendorName = "Not selected VendorName";
                vendorAddress = string.Empty;
                vendorPhone = "Nil";
            }

            Chunk c = new Chunk
               ("\n\n\n\n\n\n Purchase Request Details  \n \n",
               FontFactory.GetFont("Verdana", 15));
            Paragraph p = new Paragraph();
            p.Alignment = Element.ALIGN_CENTER;
            p.Add(c);

            Chunk chunk11 = new Chunk
           (vendorName + ", \n",
           FontFactory.GetFont("Verdana", 10));
            Paragraph p11 = new Paragraph();
            p11.Alignment = Element.ALIGN_RIGHT;
            p11.Add(chunk11);


            Chunk chunk111 = new Chunk
        (vendorAddress + ", \n",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p111 = new Paragraph();
            p111.Alignment = Element.ALIGN_RIGHT;
            p111.Add(chunk111);

            Chunk chunk1111 = new Chunk
        ("Phone : \t\t" + vendorPhone + ", \n",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p1111 = new Paragraph();
            p1111.Alignment = Element.ALIGN_RIGHT;
            p1111.Add(chunk1111);

            Chunk chunk1 = new Chunk
        ("Product Name  : \t \t",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p1 = new Paragraph();
            p1.Alignment = Element.ALIGN_LEFT;
            p1.Add(chunk1);

            Chunk chunk2 = new Chunk
       (ddlProductName.SelectedItem.ToString() + "\n",
        FontFactory.GetFont("Verdana", 10));
            p1.Add(chunk2);

            Chunk chunk3 = new Chunk
        ("Quantity  \t \t  \t \t  : \t \t",
        FontFactory.GetFont("Verdana", 10));
            Paragraph p2 = new Paragraph();
            p2.Alignment = Element.ALIGN_LEFT;
            p2.Add(chunk3);

            Chunk chunk4 = new Chunk
       (txtQty.Text + "\n",
        FontFactory.GetFont("Verdana", 10));
            p2.Add(chunk4);

            //iTextSharp.text.Table table = new iTextSharp.text.Table(grvMaterialDetails.Columns.Count);
            int productID = Convert.ToInt16(ddlProductName.SelectedValue);
            DataTable dt = purchase.GetVendorDetailsByProductId(productID, vendorId,grdSelectUniqId);
            int cols = dt.Columns.Count;
            int rows = dt.Rows.Count;
            iTextSharp.text.Table table = new iTextSharp.text.Table(cols, rows);

            for (int i = 0; i < cols; i++)
            {
                Cell cellCols = new Cell();
                Chunk chunkCols = new Chunk(dt.Columns[i].ColumnName);
                cellCols.Add(chunkCols);
                table.AddCell(cellCols);

            }

            for (int k = 0; k < rows; k++)
            {
                for (int j = 0; j < cols; j++)
                {
                    Cell cellRows = new Cell();
                   
                    Chunk chunkRows = new Chunk(dt.Rows[k][j].ToString());
                    cellRows.Add(chunkRows);
                    table.AddCell(cellRows);

                }
            }
            //for (int k = 0; k < dt.Columns.Count; k++)
            //{
            //    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(dt.Columns[k].ColumnName.Replace(",", ";") + ',');

            //    // cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#008000"));
            //    table.AddCell(cell);
            //}

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{

            //    for (int k = 0; k < dt.Columns.Count; k++)
            //    {

            //        //add separator

            //       iTextSharp.text.Cell cell = new iTextSharp.text.Cell(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
            //       table.AddCell(cell);
            //    }

            //    //append new line
               

            //} 
            document.Add(p);
            document.Add(p11);
            document.Add(p111);
            document.Add(p1111);
            document.Add(p1);
            document.Add(p2);
            document.Add(table);
        }
        document.Close();
        HttpContext.Current.Response.Buffer = true;
        // HttpContext.Current.Response.ClearContent();
        // HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=PurchaseRequest.pdf");
        HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
        HttpContext.Current.Response.End();
    }
    /// <summary>
    /// Creates the PDF document with a given content at a given location.
    /// </summary>
    /// <param name=”strFilePath”>The file path to write the new PDF to.</param>
    /// <param name=”strContent”>Content in HTML to write to the PDF.</param>
    public void CreatePDFDocument1()
    {
         string vendorName=string.Empty;
         string vendorAddress= string.Empty;
         string vendorPhone = string.Empty;
        DataSet vendorDS=new DataSet();
        int gvCount;
        //grvMaterialDetails.AllowPaging = false;
        MemoryStream MStream = new MemoryStream();
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);
        PdfWriter writer = PdfWriter.GetInstance(document, MStream);


        Phrase footPhraseImg = new Phrase("Page: ", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));
        HeaderFooter footer = new HeaderFooter(footPhraseImg, true);
        footer.Border = iTextSharp.text.Rectangle.TOP_BORDER;
        footer.Alignment = Element.ALIGN_RIGHT;
        document.Footer = footer;

        document.Open();

        iTextSharp.text.Image imghead = iTextSharp.text.Image.GetInstance(Server.MapPath("~\\images\\ebirdlogo.jpg"));
        imghead.SetAbsolutePosition(0, 0);
        imghead.Alignment = Element.ALIGN_RIGHT;
        PdfContentByte cbhead = writer.DirectContent;
        PdfTemplate tp = cbhead.CreateTemplate(350, 393);
        tp.AddImage(imghead);
        cbhead.AddTemplate(tp, 30, 740);
        Phrase headPhraseImg = new Phrase(imghead + "", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 7, iTextSharp.text.Font.NORMAL));
        HeaderFooter header = new HeaderFooter(headPhraseImg, true);
        header.Alignment = Element.ALIGN_TOP;
        header.Border = iTextSharp.text.Rectangle.TOP_BORDER;
        try
        {
            for (gvCount = 0; gvCount < grvMaterialDetails.Rows.Count; gvCount++)
            {
                int vendorId=0;
                string vendor = ((DropDownList)grvMaterialDetails.Rows[gvCount].Cells[3].FindControl("ddlVendorName")).SelectedValue;
                if (((DropDownList)grvMaterialDetails.Rows[gvCount].Cells[3].FindControl("ddlVendorName")).SelectedIndex == 0)
                {
                    vendorId = 0;
                }
                else
                {
                    if (vendor != "") 
                      vendorId = Convert.ToInt16(vendor);
                }
                if (vendorId != 0)
                {
                     vendorDS=purchase.GetVendorDetailsById(vendorId);
                     if (vendorDS.Tables[0].Rows.Count > 0 && vendorId != 0)
                     {
                         vendorName = vendorDS.Tables[0].Rows[0]["VR_VendorName"].ToString();
                         vendorAddress = vendorDS.Tables[0].Rows[0]["VR_VendorAddress"].ToString();
                         vendorPhone = vendorDS.Tables[0].Rows[0]["VR_VendorPhone"].ToString();

                     }

                }

               
                else
                {
                    vendorName = "Not selected VendorName";
                    vendorAddress = string.Empty;
                    vendorPhone = "Nil";
                }

                //int productID = Convert.ToInt16(ddlProductName.SelectedValue);
                //DataTable dt = purchase.GetVendorDetailsByProductId(productID, vendorId);
                //for (int k = 0; k < dt.Columns.Count; k++)
                //{
                //    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);

                //    // cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#008000"));
                //    table.AddCell(cell);
                //}
                Chunk c = new Chunk
                ("\n\n\n\n\n\n Purchase Request Details  \n \n",
                FontFactory.GetFont("Verdana", 15));
                Paragraph p = new Paragraph();
                p.Alignment = Element.ALIGN_CENTER;
                p.Add(c);

                Chunk chunk11 = new Chunk
            (vendorName+", \n",
            FontFactory.GetFont("Verdana", 10));
                Paragraph p11 = new Paragraph();
                p11.Alignment = Element.ALIGN_RIGHT;
                p11.Add(chunk11);


                Chunk chunk111 = new Chunk
            (vendorAddress + ", \n",
            FontFactory.GetFont("Verdana", 10));
                Paragraph p111 = new Paragraph();
                p111.Alignment = Element.ALIGN_RIGHT;
                p111.Add(chunk111);

                Chunk chunk1111 = new Chunk
            ("Phone : \t\t" +vendorPhone + ", \n",
            FontFactory.GetFont("Verdana", 10));
                Paragraph p1111 = new Paragraph();
                p1111.Alignment = Element.ALIGN_RIGHT;
                p1111.Add(chunk1111);

                Chunk chunk1 = new Chunk
            ("Product Name  : \t \t",
            FontFactory.GetFont("Verdana", 10));
                Paragraph p1 = new Paragraph();
                p1.Alignment = Element.ALIGN_LEFT;
                p1.Add(chunk1);

                Chunk chunk2 = new Chunk
           (ddlProductName.SelectedItem.ToString() + "\n",
            FontFactory.GetFont("Verdana", 10));
                p1.Add(chunk2);

                Chunk chunk3 = new Chunk
            ("Quantity  \t \t  \t \t  : \t \t",
            FontFactory.GetFont("Verdana", 10));
                Paragraph p2 = new Paragraph();
                p2.Alignment = Element.ALIGN_LEFT;
                p2.Add(chunk3);

                Chunk chunk4 = new Chunk
           (txtQty.Text + "\n",
            FontFactory.GetFont("Verdana", 10));
                p2.Add(chunk4);

                //   int columnCount = grvMaterialDetails.Columns.Count;
                //   int rowCount = grvMaterialDetails.Rows.Count;
                //   int tableRows = rowCount + 3;
                //   iTextSharp.text.Table grdTable =
                //   new iTextSharp.text.Table(columnCount, tableRows);
                //   grdTable.BorderWidth = 1;
                //  // grdTable.BorderColor = new Color();
                ////   grdTable.Cellpadding = 5;
                // //  grdTable.Cellspacing = 5;
                // //  Cell c1 = new Cell("S.No");
                // //  c1.Header = true; 
                // //  grdTable.AddCell(c1);
                ////   Cell c2 = new Cell("Item Name");
                //  // c2.Colspan = 2;
                ////   grdTable.AddCell(c2);
                //   //grdTable.Height ="12";
                //   grdTable.AddCell("Sr.No");
                //   grdTable.AddCell("ItemName");
                //   grdTable.AddCell("Unit Quantity");
                //   grdTable.AddCell("Tot.Quantity");
                //   grdTable.AddCell("Unit Price");
                //   grdTable.AddCell("Tot.Price");

                //   for (int rowCounter = 0;rowCounter < rowCount; rowCounter++)
                //   {
                //       for (int columnCounter = 0; columnCounter < columnCount; columnCounter++)
                //       {
                //           string strValue = grvMaterialDetails.Rows[rowCounter].Cells[columnCounter].Text;
                //           grdTable.AddCell(strValue);
                //       }
                //   }

                iTextSharp.text.Table table = new iTextSharp.text.Table(grvMaterialDetails.Columns.Count);

                //  table.Cellpadding = 5;

                table.Width = 100;

                //Set the column widths

                int[] widths = new int[grvMaterialDetails.Columns.Count];

                for (int x = 0; x < grvMaterialDetails.Columns.Count; x++)
                {

                    widths[x] = (int)grvMaterialDetails.Columns[x].ItemStyle.Width.Value * 20;

                    string cellText = Server.HtmlDecode(grvMaterialDetails.HeaderRow.Cells[x].Text);

                    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);

                    // cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#008000"));
                    table.AddCell(cell);

                }




                //Transfer rows from GridView to table

                //for (int i = 0; i < grvMaterialDetails.Rows.Count; i++)
                //{

                //    if (grvMaterialDetails.Rows[i].RowType == DataControlRowType.DataRow)
                //    {

                //        for (int j = 0; j < grvMaterialDetails.Columns.Count; j++)
                //        {
                //            string cellText = Server.HtmlDecode

                //                              (grvMaterialDetails.Rows[i].Cells[j].Text);

                //            //  DataSet materialDS = purchase.GetMaterialDetailsByProductID(productID);
                //            //  string cellText = materialDS.Tables[0].Rows[i][j].ToString();
                //            //string cellText = Server.HtmlDecode

                //            //                  (grvMaterialDetails.Rows[i].Cells[j].Text);

                //            iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);

                //            table.AddCell(cell);

                //        }

                //    }

                //}




                //foreach (GridViewRow row in grvMaterialDetails.Rows)
                //{
                for (int i = 0; i < grvMaterialDetails.Rows.Count; i++)
                {
                    if(i==gvCount)
                    {

                  string sno = ((Label)grvMaterialDetails.Rows[i].Cells[0].FindControl("sno")).Text;
                  string lblMaterialId = ((Label)grvMaterialDetails.Rows[i].Cells[1].FindControl("lblMaterialId")).Text;
                  string lblItmName = ((Label)grvMaterialDetails.Rows[i].Cells[1].FindControl("lblItmName")).Text;
                  string vendorname = ((DropDownList)grvMaterialDetails.Rows[i].Cells[3].FindControl("ddlVendorName")).SelectedItem.ToString();
                  string lblUnit = ((Label)grvMaterialDetails.Rows[i].Cells[1].FindControl("lblUnit")).Text;
                  string txtQuantity = ((TextBox)grvMaterialDetails.Rows[i].Cells[3].FindControl("txtQuantity")).Text;
                  string txtUnitPrice = ((TextBox)grvMaterialDetails.Rows[i].Cells[3].FindControl("txtUnitPrice")).Text;
                  string txtTotal = ((TextBox)grvMaterialDetails.Rows[i].Cells[3].FindControl("txtTotal")).Text;

                    //string sno = ((Label)row.Cells[0].FindControl("sno")).Text;
                    //string lblMaterialId = ((Label)row.Cells[1].FindControl("lblMaterialId")).Text;
                    //string lblItmName = ((Label)row.Cells[1].FindControl("lblItmName")).Text;
                    //string vendorname = ((DropDownList)row.Cells[3].FindControl("ddlVendorName")).SelectedItem.ToString();
                    //string lblUnit = ((Label)row.Cells[1].FindControl("lblUnit")).Text;
                    //string txtQuantity = ((TextBox)row.Cells[3].FindControl("txtQuantity")).Text;
                    //string txtUnitPrice = ((TextBox)row.Cells[3].FindControl("txtUnitPrice")).Text;
                    //string txtTotal = ((TextBox)row.Cells[3].FindControl("txtTotal")).Text;


                    //  string dd = ((Label)row.Cells[1].FindControl("lblUniqID")).Text;

                    //PrepareControlForExport(row);
                    table.AddCell(sno);
                    table.AddCell(lblMaterialId);
                    table.AddCell(lblItmName);
                    table.AddCell(vendorname);
                    table.AddCell(lblUnit);
                    table.AddCell(txtQuantity);
                    table.AddCell(txtUnitPrice);
                    table.AddCell(txtTotal);
                    }
                }
               // }

                Chunk chunk5 = new Chunk
           ("Total Amount  \t \t  \t \t  : \t \t",
           FontFactory.GetFont("Verdana", 12));
                Paragraph p3 = new Paragraph();
                p3.Alignment = Element.ALIGN_LEFT;
                p3.Add(chunk5);

                Chunk chunk6 = new Chunk
           (expectedAmount + "\n",
            FontFactory.GetFont("Verdana", 12));
                p3.Add(chunk6);


                Chunk chunk7 = new Chunk
         ("Date   \t  : \t \t",
         FontFactory.GetFont("Verdana", 10));
                Paragraph p4 = new Paragraph();
                p4.Alignment = Element.ALIGN_RIGHT;
                p4.Add(chunk7);

                Chunk chunk8 = new Chunk
           (lblD1.Text + "\n\n\n",
            FontFactory.GetFont("Verdana", 10));
                p4.Add(chunk8);

                document.Add(p);
                document.Add(p11);
                document.Add(p111);
                document.Add(p1111);
                document.Add(p4);
                document.Add(p1);
                document.Add(p2);
                document.Add(table);
                //document.Add(p3);
               
            }
            document.Close();
            }
      
        catch (Exception e)
        {
            throw e;
        }
        HttpContext.Current.Response.Buffer = true;
       // HttpContext.Current.Response.ClearContent();
       // HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=D:\\BindhyaChandran\\Task\\1.pdf");
        HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
        HttpContext.Current.Response.End();
    }
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is TextBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as TextBox).Text));
            }
        }
    }

    protected void ClearControls()
    {
        ddlProductName.SelectedIndex = 0;
        txtQty.Text = "1";
        txtDueDate.Text = DateTime.Now.ToShortDateString();
        txtActualLeadTime.Text = DateTime.Now.ToShortDateString();
        ddlPriority.SelectedIndex = 0;
        txtRemarks.Text = string.Empty;
        grvMaterialDetails.DataSource = null;
        grvMaterialDetails.DataBind();
    }

    public void SendRequest()
    {
       int requestTypeId = requestCreate.FindRequestTypeId("PurchaseRequest");
        //requestCreate.CreateRequest("PurchaseRequest",0, linkKey);
        //bool status = purchase.UpdateReQuestStatus(linkKey, requestTypeId, 10);

        bool status2 = purchase.UpdatePurchaseRequestStatus(generalPurchaseUniqId, 2);
        int inBoxUniqId = inBoxCreate.CreateInBox(requestTypeId, 10, linkKey);
        bool status = inBoxCreate.UpdateInBoxStatus(inBoxUniqId, 10,1, txtRemarks.Text);
        if (status)
        {
            MessageBox.Show("Forwarded Purchase Request Successfully");
            btnSend.Visible = false;
            btnSendForApproval.Visible = false;
        }
        else
        {
            MessageBox.Show("Failed to Forward.Please try again..");
        }
        GetProductionWisePurchasedItems();
    }

    protected void GeneralPurchaseRequestClearControls()
    {
        btnGeneralSendForApproval.Visible = false;
        btnGeneralForward.Visible = false;
        gvItemDetails.Visible = true;
        SetInitialRow();
        txtGeneralPurchaseRemarks.Text = string.Empty;
        ddlGeneralPriority.SelectedIndex = 0;
        txtGeneralActualLeadDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
        txtGeneralExpectedLeadDate.Text = DateTime.Now.ToString("MM/dd/yyyy"); 
        btnGeneralPurchaseRequestUpdate.Visible = false;
        btnGeneralPurchaseCompleted.Visible = true;
       lblErrMessage.Text = string.Empty;
       lblErrMessage.Visible = false;
       grvViewItemDetailsGeneral.Visible = false;
       Button3.Visible = true;
       Button5.Visible = false;
       btnGeneralPurchaseSubmit.Visible = false;
       btnGeneralPurchaseSubmit1.Visible = false;

    }
    #endregion

  

}
